#!/usr/bin/env python

from twisted.web.client import HTTPClientFactory, HTTPPageGetter, _parse
from twisted.internet import reactor, protocol
from twisted.internet import defer


class RoboHTTPFeeder(HTTPPageGetter):
    def connectionMade(self):
        print "Estableciendo comnunicacion"
        HTTPPageGetter.connectionMade(self)
        print self.headers
        
    def handleHeader(self, key, value):
        #print "Tenemos Headers %s con un valor de %s\n" %(key, value)
        HTTPPageGetter.handleHeader(self, key, value)
        #print self.headers
        
 #   def handleResponse(self, response):
  #      print 'handleResponse'
   #     self.factory.gotHeaders(self.headers)
    #    print self.factory.cookies
     #   print self.headers
      #  self.factory.response = response


def print_page():
        print 'aaaaa'
        
        
class RoboHTTPFeederFactory(HTTPClientFactory):
    protocol = RoboHTTPFeeder
    response = None

    stdsHeaders = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', \
                    'Accept-Language': 'es-MX,es;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive',\
                    'Host': 'www.fuerzas-armadas.com'}
    
    def __init__(self, url, method='GET', postdata=None, headers=stdsHeaders,
                 agent="Robocop Getter", timeout=0, cookies=None,
                 followRedirect=False, redirectLimit=5,
                 afterFoundGet=False):
        HTTPClientFactory.__init__(self, url, method, postdata, headers, agent, timeout, cookies, followRedirect, redirectLimit, afterFoundGet)
        #HTTPClientFactory.deferred.addCallback(print_page)
        self.deferred = defer.Deferred()
        self.deferred.addCallback(print_page)
        
    def gotHeaders(self, headers):
        print "gotHeaders"
        HTTPClientFactory.gotHeaders(self, headers)
    
    
    def page(self, page):
        print 'en page'
        HTTPClientFactory.page(self, page)


class StageAttack(object):
    
    def __init__(self, uri):
        self.MyFactory = RoboHTTPFeederFactory(uri)
        schema, self.host, self.port, self.path = _parse(uri)
        reactor.connectTCP(self.host, self.port, self.MyFactory)
       
   
    def test(self):
        print 'hola lola'
    
    def StageOne(self):
        print 'hola22'
        print self.MyFactory.response
        
        
    
if __name__ == "__main__":
    #reactor.connectTCP('www.fuerzas-armadas.com', 80, RoboHTTPFeederFactory('http://www.fuerzas-armadas.com'))
    #print "print page"
    #reactor.run()
    a = StageAttack('http://www.fuerzas-armadas.com')
    a.StageOne()
    reactor.run()
    
    